import React, { useEffect, useState, useRef, useCallback } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { Button } from 'antd-mobile';
import { LeftOutline } from 'antd-mobile-icons';

// 设置安全密钥
window._AMapSecurityConfig = {
    securityJsCode: "49dde4b4204461098b571089034f6a9d", // 填写高德地图的安全密钥
};

const App = () => {
    const navigate = useNavigate();
    const [querysearch] = useSearchParams();
    // const address = querysearch.get('address'); // 获取URL参数中的地址
    const address = "果聚惠生鲜超市(厚福盈小区店)";
    const title = querysearch.get('title');
    const [distance, setDistance] = useState('');
    const [map, setMap] = useState(null);
    const [errorMessage, setErrorMessage] = useState('');
    const [driving, setDriving] = useState(null);
    const AMapRef = useRef(null);
    const [startPosition, setStart] = useState(null);
    const [endPosition, setEnd] = useState(null);
    const [routeInstructions, setRouteInstructions] = useState('');
    const [transing, setTransing] = useState(null);
    const [currentNavigationType, setCurrentNavigationType] = useState(null);
    const [costtime, setCosttime] = useState('');
    const [isLoading, setIsLoading] = useState(false);

    const mapContainerRef = useRef(null);
    const panelRef = useRef(null);

    // 初始化地图和导航功能
    const initializeMap = useCallback(async () => {
        try {
            const AMap = await AMapLoader.load({
                key: 'de6f23e226a7544ed0cacd9a3603790d',
                version: '2.0',
                plugins: ['AMap.Driving', 'AMap.Geocoder', 'AMap.Geolocation', 'AMap.Transfer'],
            });
            AMapRef.current = AMap;

            // 获取当前定位
            const geolocation = new AMap.Geolocation({
                enableHighAccuracy: true,
                timeout: 10000,
                zoomToAccuracy: true,
            });
            const position = await new Promise((resolve, reject) => {
                geolocation.getCurrentPosition((status, result) => {
                    if (status === 'complete') {
                        resolve(result.position);
                    } else {
                        reject(new Error('定位失败'));
                    }
                });
            });
            setStart(position);

            // 地址转坐标
            const geocoder = new AMap.Geocoder();
            const geocodeResult = await new Promise((resolve, reject) => {
                geocoder.getLocation(address, (status, result) => {
                    if (status === 'complete' && result.info === 'OK') {
                        resolve(result.geocodes[0].location);
                    } else {
                        reject(new Error('地址转换坐标失败'));
                    }
                });
            });
            setEnd(geocodeResult);

            // 初始化地图
            const mapInstance = new AMap.Map(mapContainerRef.current, {
                zoom: 18,
                center: geocodeResult,
                draggable: false,
            });

            // 添加标记
            new AMap.Marker({
                position: geocodeResult,
                map: mapInstance,
                icon: 'https://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
            });

            // 初始化导航插件
            const drivingInstance = new AMap.Driving({ map: mapInstance });
            const transferInstance = new AMap.Transfer({
                map: mapInstance,
                city: '保定市',
                panel: panelRef.current,
                policy: AMap.TransferPolicy.LEAST_TIME,
            });

            setMap(mapInstance);
            setDriving(drivingInstance);
            setTransing(transferInstance);
        } catch (error) {
            console.error('初始化失败:', error);
            setErrorMessage(error.message);
        } finally {
            setIsLoading(false);
        }
    }, [address]);

    useEffect(() => {
        setIsLoading(true);
        initializeMap();
    }, [initializeMap]);

    // 清除地图覆盖物
    const clearMapOverlays = useCallback(() => {
        if (map) {
            map.clearMap();
            if (currentNavigationType === 'transfer' && driving) {
                map.remove(driving);
            }
            if (currentNavigationType === 'driving' && transing) {
                map.remove(transing);
            }
        }
    }, [map, driving, transing, currentNavigationType]);

    // 驾车导航
    const showDriver = useCallback(() => {
        if (map && driving && AMapRef.current && startPosition && endPosition) {
            clearMapOverlays();
            driving.search(
                new AMapRef.current.LngLat(startPosition.lng, startPosition.lat),
                new AMapRef.current.LngLat(endPosition.lng, endPosition.lat),
                (status, result) => {
                    if (status === 'complete') {
                        const route = result.routes[0];
                        const instructions = route.steps.map(step => step.instruction).join('\n');
                        setDistance(route.distance);
                        setRouteInstructions(instructions);
                        setCurrentNavigationType('driving');
                        setCosttime(route.time);
                    } else {
                        console.error('驾车导航失败:', status);
                        setErrorMessage('驾车导航失败，请重试');
                    }
                }
            );
        }
    }, [map, driving, startPosition, endPosition, clearMapOverlays]);

    // 公交导航
    const showTransfer = useCallback(() => {
        if (map && transing && AMapRef.current && startPosition && endPosition) {
            clearMapOverlays();
            transing.search(
                new AMapRef.current.LngLat(startPosition.lng, startPosition.lat),
                new AMapRef.current.LngLat(endPosition.lng, endPosition.lat),
                (status, result) => {
                    if (status === 'complete' && result.plans.length > 0) {
                        setCosttime(result.plans[0].time);
                        setCurrentNavigationType('transfer');
                    } else {
                        console.error('公交导航失败:', status);
                        setErrorMessage('公交导航失败，请重试');
                    }
                }
            );
        }
    }, [map, transing, startPosition, endPosition, clearMapOverlays]);

    return (
        <div style={{ position: 'relative', marginBottom: '40px' }}>
            <button
                onClick={() => navigate('index')}
                style={{
                    position: 'fixed',
                    zIndex: '5',
                    fontSize: '20px',
                    border: 'none',
                    backgroundColor: 'rgba(0,0,0,.1)',
                    borderRadius: '50%',
                    top: '5px',
                    left: '5px',
                }}
            >
                <LeftOutline />
            </button>

            <div ref={mapContainerRef} id="container" style={{ width: '100%', height: '500px' }}></div>
            {errorMessage && <p style={{ color: 'red' }}>{errorMessage}</p>}
            <div style={{ display: 'flex', justifyContent: 'space-around' }}>
                <div style={{ width: '60%' }}>
                    <h3>{title}</h3>
                    <p><small>{address}</small></p>
                </div>
                <div style={{ textAlign: 'right', marginTop: '15px' }}>
                    <div>咖啡订单</div>
                    <div>{distance ? <p style={{ margin: '5px 0' }}>{Math.round(distance / 1000)} 公里</p> : ''}</div>
                    <div>{costtime ? <p style={{ margin: '5px 0' }}>{(costtime / 60).toFixed(0)} 分钟</p> : ''}</div>
                </div>
            </div>
            <div style={{ position: 'fixed', bottom: '0', left: '100px', textAlign: 'center', display: 'flex', zIndex: '5' }}>
                <Button size="small" color="primary" onClick={showDriver} style={{ marginRight: '10px' }}>
                    驾车导航
                </Button>
                <Button size="small" color="success" onClick={showTransfer}>
                    公交车导航
                </Button>
            </div>

            {currentNavigationType === 'driving' && routeInstructions && (
                <div style={{ marginTop: '20px', padding: '10px', backgroundColor: '#f9f9f9', border: '1px solid #ddd' }}>
                    <h3>路径规划:</h3>
                    <pre style={{ fontSize: '15px' }}>{routeInstructions}</pre>
                </div>
            )}
            <div
                ref={panelRef}
                id="panel"
                style={{
                    width: '100%',
                    height: '300px',
                    overflowY: 'scroll',
                    margin: '20px 0',
                    display: currentNavigationType === 'transfer' ? 'block' : 'none',
                }}
            ></div>
        </div>
    );
};

export default App;